package com.octopus.core;

import com.octopus.core.utils.JsonUtils;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import lombok.NonNull;

/**
 * 存储临时数据
 *
 * @author yang_shoulai@hoperun.com
 * @date 2019/08/05
 */
public class Extras {

  private Map<String, Object> extras = new HashMap<>();

  public Extras put(@NonNull String name, Object extra) {
    this.extras.put(name, extra);
    return this;
  }

  public Extras put(@NonNull Map<String, Object> extras) {
    this.extras.putAll(extras);
    return this;
  }

  @SuppressWarnings("unchecked")
  public <T> T get(@NonNull String name, @NonNull Class<T> clz) {
    return (T) this.extras.get(name);
  }

  public Integer getInteger(@NonNull String name) {
    return this.get(name, Integer.class);
  }

  public Integer optInteger(@NonNull String name, Integer def) {
    Integer value = this.getInteger(name);
    return value == null ? def : value;
  }

  public Long getLong(@NonNull String name) {
    return this.get(name, Long.class);
  }

  public Long optLong(@NonNull String name, Long def) {
    Long value = this.getLong(name);
    return value == null ? def : value;
  }

  public String getString(@NonNull String name) {
    return this.get(name, String.class);
  }

  public String optString(@NonNull String name, String def) {
    String value = this.getString(name);
    return value == null ? def : value;
  }

  public Boolean getBoolean(@NonNull String name) {
    return this.get(name, Boolean.class);
  }

  public Boolean optBoolean(@NonNull String name, Boolean def) {
    Boolean value = this.getBoolean(name);
    return value == null ? def : value;
  }

  public Date getDate(@NonNull String name) {
    return this.get(name, Date.class);
  }

  public Date optDate(@NonNull String name, Date def) {
    Date value = this.getDate(name);
    return value == null ? def : value;
  }

  public Float getFloat(@NonNull String name) {
    return this.get(name, Float.class);
  }

  public Float optFloat(@NonNull String name, Float def) {
    Float value = this.getFloat(name);
    return value == null ? def : value;
  }

  public Double getDouble(@NonNull String name) {
    return this.get(name, Double.class);
  }

  public Double optDouble(@NonNull String name, Double def) {
    Double value = this.getDouble(name);
    return value == null ? def : value;
  }

  @Override
  public String toString() {
    return JsonUtils.toJson(this.extras);
  }

  public boolean isEmpty() {
    return this.extras.isEmpty();
  }

  public boolean exist(@NonNull String name) {
    return this.extras.containsKey(name);
  }
}
